<?php

use Medoo\Medoo;

/**
 * https://medoo.in/api/new
 * http://www.querylist.cc/docs/guide/v4/http-client
 */
chdir(__DIR__);
require_once  realpath('..')  . '/vendor/autoload.php';
$config = include 'database.php';

echo '爬虫开始' . PHP_EOL;

$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://www.cadillac.com.cn/api/mapdealer.ashx');
$html = (string)$res->getBody();


$count = preg_match_all('/dealerinfo\[\d+\] = new Array\((.*)\);/U', $html, $match);
//$data = QueryList::html($html)->find('h3')->texts();

if ($count > 0) {
    $db = new Medoo($config);
    $db->delete('tDealer', ['sBrand' => '凯迪拉克']);
    $list = $match[1];

    foreach ($list as $item) {
        $info = str_replace('\'', '', $item);
        $dealer = explode(',', $info);

        $db->insert('tDealer', [
            'sDealerName' => $dealer[1],
            'nBrandID' => $dealer[0],
            'sBrand' => '凯迪拉克',
            'sProvince' => $dealer[5],
            'sCity' => $dealer[6],
            'sAddress' => $dealer[2],
            'sSaleCall' => $dealer[7],
            'sLatitude' => $dealer[3],
            'sLongitude' => $dealer[4],
            'dUpdateTime' => Medoo::raw('now()'),
            'sManufacturer' => '上海通用',
        ]);
        echo "{$dealer[1]}完成" . PHP_EOL;

    }
    echo '爬虫完成' . PHP_EOL;
}
